#pragma once
#include "../Common/Common.h"

class Runable
{
public:
	Runable(void) : m_queue_updates(new UpdateContainer), m_updates(new UpdateContainer)
	{
	}

	virtual ~Runable(void)
	{
		boost::lock_guard<boost::mutex> g(m_update_mutex);

		UpdateContainer::iterator it = m_queue_updates->begin();
		while (it != m_queue_updates->end())
		{
			(*it)(false);
			++it;
		}

		it = m_updates->begin();
		while (it != m_updates->end())
		{
			(*it)(false);
			++it;
		}

	}

	virtual void update(uint32 timeElapse)
	{
		UpdateContainer::iterator it = m_updates->begin();
		while (it != m_updates->end())
		{
			(*it)(true);
			++it;
		}

		m_updates->clear();

		{
			boost::lock_guard<boost::mutex> g(m_update_mutex);
			if (m_queue_updates->empty())
				return;

			boost::swap(m_queue_updates,m_updates);
		}
	}

	void queueHandler(const boost::function1<void,bool>& h)
	{
		boost::lock_guard<boost::mutex> g(m_update_mutex);
		m_queue_updates->push_back(h);
	}

private:
	typedef std::vector<boost::function1<void,bool> > UpdateContainer;
	boost::scoped_ptr<UpdateContainer> m_queue_updates;
	boost::scoped_ptr<UpdateContainer> m_updates;

	boost::mutex m_update_mutex;
};


class SimpleHandle
{
public:
	SimpleHandle(const boost::function0<void>& h) : m_h(h)
	{

	}
	void operator()(bool)
	{
		m_h();
	}

private:
	boost::function0<void> m_h;
};
